<template>
  <el-tooltip
    :content="$tr('Open existing project')"
    v-if="buttonType == 'tool'"
  >
    <el-button @click="onShow">
      <el-icon>
        <folder-opened />
      </el-icon>
    </el-button>
  </el-tooltip>
  <el-button @click="onShow" v-else>
    <el-icon>
      <folder-opened />
    </el-icon>
    <text v-html="'&nbsp;'" />
    {{ $tr("Open Project") }}
  </el-button>
  <el-dialog v-model="show">
    <el-form>
      <el-form-item label="项目路径">
        <directory-selector v-model="config.workdir"></directory-selector>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">Cancel</el-button>
        <el-button type="primary" @click="openProject">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { openProject } from "@/api/cards";
import { reactive, ref } from "vue";
import { defineComponent } from "vue-demi";
import { FolderOpened } from "@element-plus/icons-vue";
import DirectorySelector from "@/components/panels/DirectorySelector.vue";
import store from "@/api/store";
import { tr } from "@/assets/translation/trans";
import { ElMessage } from "element-plus";
import { getParentDir } from "@/utils/utils";
export default defineComponent({
  components: { FolderOpened, DirectorySelector },
  props: {
    buttonType: {
      type: String,
      required: true,
    },
  },
  setup() {
    return {
      show: ref(false),
      config: reactive({ name: "", workdir: store.state.workdir }),
    };
  },
  methods: {
    async openProject() {
      try {
        await openProject(this.config.workdir);
        this.show = false;
        window.open(window.location.origin, "_self");
      } catch (err) {
        ElMessage.error(tr("Cannot open project") + ":" + err);
        console.error(err);
      }
    },
    onShow() {
      this.config.workdir = getParentDir(store.state.workdir);
      this.show = true;
    },
  },
});
</script>

<style></style>
